import { app, BrowserWindow, ipcMain } from 'electron'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
// import os from 'node:os'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null

// 注册自定义协议
function registerCustomProtocol() {
  // 注册 modelSearch 协议
  if (process.defaultApp) {
    if (process.argv.length >= 2) {
      app.setAsDefaultProtocolClient('modelSearch', process.execPath, [path.resolve(process.argv[1])])
    }
  } else {
    app.setAsDefaultProtocolClient('modelSearch')
  }
}

// 处理协议调起
function handleProtocolLaunch() {
  console.log('Setting up protocol launch handlers...')
  
  // 处理 macOS 的协议调起
  app.on('open-url', (event, url) => {
    console.log('macOS open-url event:', url)
    event.preventDefault()
    handleProtocolUrl(url)
  })

  // 处理 Windows 的协议调起
  app.on('second-instance', (_event, commandLine) => {
    console.log('Second instance detected, command line:', commandLine, '_event:', _event, 'win:', win)
    
    // 有人试图运行第二个实例，我们应该聚焦我们的窗口
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()
    }

    // 处理命令行参数中的协议 URL
    const protocolUrl = commandLine.find(arg => arg.startsWith('modelsearch://'))
    console.log('protocolUrl:', protocolUrl)
    if (protocolUrl) {
      console.log('Found protocol URL in second instance:', protocolUrl)
      handleProtocolUrl(protocolUrl)
    }
  })

  // 处理首次启动时的协议参数
  const gotTheLock = app.requestSingleInstanceLock()
  if (!gotTheLock) {
    console.log('Another instance is running, quitting...')
    app.quit()
    return
  }

  // 检查启动参数中是否有协议 URL
  const protocolUrl = process.argv.find(arg => arg.startsWith('modelSearch://'))
  if (protocolUrl) {
    console.log('Found protocol URL in startup args:', protocolUrl)
    handleProtocolUrl(protocolUrl)
  }
}

// 处理协议 URL
function handleProtocolUrl(url: string) {
  console.log('Received protocol URL:', url)
  
  // 解析 URL 参数
  const urlObj = new URL(url)
  const filePath = urlObj.searchParams.get('file')
  
  if (filePath) {
    // 读取临时文件
    readTempFile(filePath)
  }
}

// 消息队列，用于存储等待发送的消息
let messageQueue: Array<{channel: string, data: any}> = []

// 读取临时文件
function readTempFile(filePath: string) {
  try {
    // 确保文件路径在临时目录内（安全考虑）
    // const tempDir = os.tmpdir()
    const resolvedPath = path.resolve(filePath)
    
    // if (!resolvedPath.startsWith(tempDir)) {
    //   console.error('File path is not in temp directory:', filePath)
    //   return
    // }

    // 检查文件是否存在
    if (!fs.existsSync(resolvedPath)) {
      console.error('File does not exist:', resolvedPath)
      return
    }

    // 读取文件内容
    const fileContent = fs.readFileSync(resolvedPath, 'utf-8')
    console.log('File content read successfully, length:', fileContent.length)

    // 准备要发送的数据
    const messageData = {
      filePath: resolvedPath,
      content: fileContent,
      timestamp: new Date().toISOString()
    }

    // 尝试发送消息到渲染进程
    sendMessageToRenderer('file-content-received', messageData)

    // 可选：删除临时文件
    // fs.unlinkSync(resolvedPath)
    
  } catch (error) {
    console.error('Error reading temp file:', error)
  }
}

// 发送消息到渲染进程，如果渲染进程未准备好则加入队列
function sendMessageToRenderer(channel: string, data: any) {
  if (win && win.webContents.isLoading()) {
    // 渲染进程还在加载中，将消息加入队列
    console.log('Renderer is still loading, queuing message:', channel)
    messageQueue.push({ channel, data })
  } else if (win) {
    // 渲染进程已准备好，直接发送消息
    console.log('Sending message to renderer:', channel)
    win.webContents.send(channel, data)
  } else {
    // 窗口不存在，将消息加入队列
    console.log('Window not ready, queuing message:', channel)
    messageQueue.push({ channel, data })
  }
}

// 处理队列中的消息
function processMessageQueue() {
  if (messageQueue.length > 0 && win) {
    console.log('Processing message queue, count:', messageQueue.length)
    const messages = [...messageQueue]
    messageQueue = []
    
    messages.forEach(({ channel, data }) => {
      win?.webContents.send(channel, data)
    })
  }
}

// 处理渲染进程的 IPC 消息
function setupIpcHandlers() {
  // 处理文件上传完成的通知
  ipcMain.on('file-upload-completed', (_event, data) => {
    console.log('File upload completed:', data)
    
    // 可以在这里处理上传完成后的逻辑
    // 比如删除临时文件、显示通知等
  })

  // 处理文件上传失败的通知
  ipcMain.on('file-upload-failed', (_event, error) => {
    console.error('File upload failed:', error)
  })
}

function createWindow() {
  win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      nodeIntegration: false,
      contextIsolation: true,
    },
  })

  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
    
    // 渲染进程加载完成后，处理队列中的消息
    processMessageQueue()
  })

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

app.whenReady().then(() => {
  // 注册自定义协议
  registerCustomProtocol()
  
  // 设置 IPC 处理器
  setupIpcHandlers()
  
  // 处理协议调起
  handleProtocolLaunch()
  
  // 创建窗口
  createWindow()
})
